package com.zyq.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zyq.exception.CustomException;
import com.zyq.model.common.BaseDto;
import com.zyq.model.common.ResponseBean;
import com.zyq.model.entity.Article;
import com.zyq.model.entity.Message;
import com.zyq.model.request.ArticleDto;
import com.zyq.model.request.ContentDto;
import com.zyq.service.IArticleService;
import com.zyq.service.IMessageService;
import com.zyq.service.IUserService;
import com.zyq.util.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * 文章Controller
 *
 * @author zyq
 * @date 2021-12-02
 */
@Api( tags = "文章接口")
@RestController
@RequestMapping("/article")
public class ArticleController
{
    @Autowired
    private IArticleService articleService;

    @Autowired
    private IMessageService messageService;


    @Autowired
    private IUserService userService;


    @Autowired
    private UserUtil userUtil;

    /**
     * 管理员获取文章列表
     */
    @ApiOperation("管理员获取文章列表")
    @GetMapping("/adminArticleList")
    public ResponseBean adminList(ArticleDto article , @RequestHeader String Authorization){
        StringBuilder orderByStr = new StringBuilder();
        if(article.getSidx()!=null && article.getSord()!=null){
            orderByStr.append(article.getSidx());
            orderByStr.append(" ");
            orderByStr.append(article.getSord());
        }
        PageHelper.startPage(article.getPageNum(), article.getPageSize(),orderByStr.toString());
        List<Article> list = articleService.selectArticleListByAdmin(article.getArticle());
        PageInfo<Article> selectPage = new PageInfo<Article>(list);
        if (list == null || list.size() < 0) {
            throw new CustomException("查询失败(Query Failure)");
        }
        Map<String, Object> result = new HashMap<String, Object>(16);
        result.put("total", selectPage.getTotal());
        result.put("pages", selectPage.getPages());
        result.put("article", selectPage.getList());
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
    }
    /**
     * 用户获取文章列表(标题、作者、文章内容模糊查询)
     */
    @ApiOperation("用户获取文章列表")
    @GetMapping("/userList")
    public ResponseBean userList(ContentDto article ){
        PageHelper.startPage(article.getPageNum(), article.getPageSize());
        List<Article> list = articleService.selectArticleList(article);
        PageInfo<Article> selectPage = new PageInfo<>(list);
        if (list == null || list.size() < 0) {
            throw new CustomException("查询失败(Query Failure)");
        }
        Map<String, Object> result = new LinkedHashMap<>(16);
        result.put("total", selectPage.getTotal());
        result.put("pages", selectPage.getPages());
        result.put("data", selectPage.getList());
        result.put("data",list);
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
//        StringBuilder orderByStr = new StringBuilder();
//        if(params.get("sidx")!=null && params.get("sord")!=null){
//            orderByStr.append(params.get("sidx").toString());
//            orderByStr.append(" ");
//            orderByStr.append(params.get("sord").toString());
//        }
//        PageHelper.startPage(Integer.parseInt(params.get("page").toString()),Integer.parseInt(params.get("rows").toString()),orderByStr.toString());
//        Article article = new Article()
//                .setContent(params.get("param").toString())
//                .setTitle(params.get("param").toString())
//                .setUserName(params.get("param").toString());
//        List<Article> list = articleService.selectArticleList(article);
//        PageInfo<Article> selectPage = new PageInfo<Article>(list);
//        if (list == null || list.size() < 0) {
//            throw new CustomException("查询失败(Query Failure)");
//        }
//        Map<String, Object> result = new HashMap<String, Object>(16);
//        result.put("count", selectPage.getTotal());
//        result.put("data", selectPage.getList());
//        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
    }
    /**
     * 获取文章详细信息
     */
    @ApiOperation("获取文章详细信息")
    @GetMapping(value = "/{id}")
    public ResponseBean getInfo(@PathVariable("id") Long id)
    {
        Map<String,Object> result = new HashMap<>();
        result.put("article",articleService.selectArticleById(id));
        Subject subject = SecurityUtils.getSubject();
        // 登录了返回true
        if (subject.isAuthenticated()) {

            result.put("dianzangflag",articleService.selectArticleGetLike(id,userUtil.getUserId()));
            result.put("shoucangflag",articleService.selectArticleCollect(id,userUtil.getUserId()));
        }else{
            result.put("dianzangflag","暂未登录");
            result.put("shoucangflag","暂未登录");
        }

        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
    }

    /**
     * 新增文章
     */
    @RequiresRoles(value = {"医生","管理员"},logical = Logical.OR)
    @ApiOperation("发布文章")
    @PostMapping(value = "insertArticle")
    public ResponseBean add(@RequestBody Article article,@RequestHeader String Authorization)
    {
        if(articleService.insertArticle(article)>0) {
            List<Long> ids = userService.selectFans(article.getUserId());
            for(int i = 0 ; i < ids.size() ; i++){
                Message message = new Message()
                        .setDetail("发布")
                        .setUserId(ids.get(i))
                        .setAId(article.getUserId())
                        .setBId(article.getId());
                messageService.insertMessage(message);
            }

            return new ResponseBean(HttpStatus.OK.value(), "新增成功", null);
        }else{
            return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), "新增失败", null);
        }
    }

    /**
     * 修改文章
     */
//    @RequiresRoles("管理员")
    @ApiOperation("修改文章")
    @PutMapping
    public ResponseBean edit(@RequestBody Article article)
    {
        if(articleService.updateArticle(article)>0) {
            return new ResponseBean(HttpStatus.OK.value(), "修改成功", null);
        }else{
            return new ResponseBean(HttpStatus.OK.value(), "修改失败", null);
        }
    }

    /**
     * 删除文章
     */
    @ApiOperation("删除文章")
//    @RequiresRoles(value = {"管理员","医生"})
    @DeleteMapping("/{ids}")
    public ResponseBean remove(@PathVariable Long[] ids)
    {
        if(articleService.deleteArticleByIds(ids)>0) {
            return new ResponseBean(HttpStatus.OK.value(), "删除成功", null);
        }else{
            return new ResponseBean(HttpStatus.OK.value(), "删除失败", null);
        }
    }


    @ApiOperation("用户获取收藏的文章")
    @GetMapping("/articleListByCollectUserId")
    @RequiresAuthentication
    public ResponseBean adminList(BaseDto baseDto , @RequestHeader String Authorization){
        StringBuilder orderByStr = new StringBuilder();
        if(baseDto.getSidx()!=null && baseDto.getSord()!=null){
            orderByStr.append(baseDto.getSidx());
            orderByStr.append(" ");
            orderByStr.append(baseDto.getSord());
        }
        PageHelper.startPage(baseDto.getPageNum(), baseDto.getPageSize(),orderByStr.toString());
        List<Article> list = articleService.selectArticleListByCollect();
        PageInfo<Article> selectPage = new PageInfo<Article>(list);
        if (list == null || list.size() < 0) {
            throw new CustomException("查询失败(Query Failure)");
        }
        Map<String, Object> result = new HashMap<String, Object>(16);
        result.put("total", selectPage.getTotal());
        result.put("pages", selectPage.getPages());
        result.put("article", selectPage.getList());
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
    }

}
